"""Splunk credential management."""

import json
import typing
from urllib import parse

from cki_lib import logger
from cki_lib import session

from . import secrets
from . import token

LOGGER = logger.get_logger(__name__)
SESSION = session.get_session(__name__)


@token.register_token('splunk_hec_token')
class SplunkHecToken(token.Token):
    """Splunk HEC token."""

    def _validate_token(self, token_version: str, meta: dict[str, typing.Any]) -> None:
        """Validate a token version."""
        token_secret = secrets.secret(self.full_token_name(token_version))
        data = json.dumps({'index': index}) if (index := meta.get('index')) else ''
        result = SESSION.post(parse.urljoin(meta['endpoint_url'], 'services/collector'), data=data,
                              headers={'Authorization': f'Splunk {token_secret}'})
        if (result.json() or {}).get('code') not in {5, 12}:
            result.raise_for_status()
